import React, {useState, useRef} from 'react';
import {View, StyleSheet, StyleProp, ViewStyle} from 'react-native';
import {Message} from './../index';
import {useEffect} from 'react';
import Item from './Item';

interface IProps {
  data: Message[];
  maxTrack: number;
  style?: StyleProp<ViewStyle>;
}

export interface IBarrage extends Message {
  trackIndex: number;
  isFree?: Boolean;
}

// 计算弹幕位置添加
function addBarrage(data: Message[], maxTrack: number, list: IBarrage[][]) {
  for (let i = 0; i < data.length; i++) {
    const trackIndex = getTrackIndex(list, maxTrack);
    if (trackIndex < 0) {
      continue;
    }
    if (!list[trackIndex]) {
      list[trackIndex] = [];
    }
    const barrage = {
      ...data[i],
      trackIndex,
    };
    list[trackIndex].push(barrage);
  }
  return list;
}

// 获取可以放置的轨道下标

function getTrackIndex(list: IBarrage[][], maxTrack: number) {
  for (let i = 0; i < maxTrack; i++) {
    let barrageOfTrack = list[i];
    if (!barrageOfTrack || barrageOfTrack.length === 0) {
      return i;
    }
    if (barrageOfTrack[barrageOfTrack.length - 1].isFree) {
      return i;
    }
  }
  return -1;
}

const Barrage: React.FC<IProps> = props => {
  const {data, maxTrack, style} = props;
  const [list, setList] = useState<IBarrage[][]>([
    data.map(item => ({...item, trackIndex: 0})),
  ]);
  const listRef = useRef<IBarrage[][]>([]);

  useEffect(() => {
    setList(item => addBarrage(data, maxTrack, item));
  }, [data, maxTrack]);

  useEffect(() => {
    listRef.current = list;
  }, [list]);

  const outside = (data: IBarrage) => {
    const newList = listRef.current.slice();
    const {trackIndex} = data;
    if (newList.length > 0) {
      newList[trackIndex] = newList[trackIndex].filter(
        item => item.id !== data.id,
      );
      setList(newList);
      // const deleteIndex = newList.indexOf(data);
      // if (deleteIndex > -1) {
      //   newList.splice(deleteIndex, 1);
      // }
    }
  };

  const renderItem = (item: IBarrage[]) => {
    return item.map(barrage => {
      return (
        <Item
          data={barrage}
          key={barrage.id}
          outside={dataItem => outside(dataItem)}
        />
      );
    });
  };

  return (
    <View style={[styles.container, style]}>
      {list.map(item => renderItem(item))}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    top: 0,
  },
});

export default Barrage;
